<template>
  <el-row class="bg-indigo-500 min-h-screen" @keyup.enter="submitForm(ruleFormRef)">

    <el-col class="flex items-center justify-center bg-cover" :lg="16" :md="12"
            style="background-image: url('/src/assets/images/16541664536_1780x1244.jpg');">
      <div class="px-10 bg-opacity-50 bg-gray-500 pb-10 pt-10">
        <div class="font-bold text-5xl text-light-50 mb-4 text-gray-800">
          <span>家和易家居</span>
        </div>
        <div class="text-light-50 text-xl text-gray-800">
          全屋定制线下门店解决方案
        </div>
      </div>
    </el-col>

    <el-col class="bg-light-50 flex items-center justify-center flex-col" :lg="8" :md="12"
            :style="{boxShadow: `var(--el-box-shadow-lighter)`}">
      <div class="font-bold text-3xl mb-4 text-gray-800">
        登录
      </div>
      <div class="flex items-center justify-center my-5 text-gray-300 space-x-2">
        <span class="h-[1px] w-16 bg-gray-300"></span>
        <span>账号密码登录</span>
        <span class="h-[1px] w-16 bg-gray-300"></span>
      </div>
      <el-form class="w-[350px]" status-icon ref="ruleFormRef" :rules="loginRules" :model="form">
        <el-form-item prop="userName">
          <el-input clearable size="large" :disabled="loading"
                    v-model.trim="form.userName" @input="form.password = null" ref="userFocus"
                    placeholder="请输入用户名">
            <template #prefix>
              <el-icon class="el-input__icon">
                <user/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input show-password clearable size="large" :disabled="loading"
                    v-model.trim="form.password" ref="passFocus" type="password" autocomplete="off"
                    placeholder="请输入密码">
            <template #prefix>
              <el-icon class="el-input__icon">
                <lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="w-[350px]" color="#6366f1" :loading="loading" type="primary"
                     @click="submitForm(ruleFormRef)">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中</span>
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button class="w-[350px]" :disabled="loading" @click="clearForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-col>

  </el-row>
</template>

<script lang="ts" setup>
import {nextTick, reactive, ref} from "vue";
import {ElNotification, FormInstance, FormRules} from "element-plus";
import {useStore} from "@/store";
import {doLogin} from "@/api/login";
import {useRouter} from "vue-router";
import Axios from "axios";

const router = useRouter()

//用户名密码聚焦
const userFocus = ref()
const passFocus = ref()
nextTick(() => {
  userFocus.value.focus()
})

//登录中
const loading = ref(false)

const form = reactive({
  userName: null,
  password: null,
})

function clearForm() {
  form.userName = null
  form.password = null
  nextTick(() => {
    userFocus.value.focus()
  })
}

const ruleFormRef = ref<FormInstance>()

const loginRules = reactive<FormRules>({
  userName: [
    {
      required: true,
      message: "请输入用户名！",
      trigger: "blur",
    }, {
      min: 4,
      max: 20,
      message: "字符必须大于4位小于20位！",
      trigger: "blur",
    }
  ],
  password: [
    {
      required: true,
      message: "请输入密码！",
      trigger: "blur",
    }, {
      min: 5,
      max: 20,
      message: "字符必须大于5位小于20位！",
      trigger: "blur",
    }
  ]
})

const ServiceAbc = Axios.create({
  baseURL: '/ipaddr',
  timeout: 20000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
})

//登录方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      loading.value = true

      ServiceAbc.get('').then(ttt => {

        doLogin({
          userName: form.userName,
          password: form.password,
          location: ttt.data.result.ad_info.nation + " " + ttt.data.result.ad_info.province + " " + ttt.data.result.ad_info.city,
          ipaddr: ttt.data.result.ip
        }).then(result => {
          if (result.data.code === 200) {
            const store = useStore();
            store.setLogin(result.data.data.tokenValue)
            store.setUser({userId: result.data.data.loginId})
            ElNotification({
              title: "登录成功",
              type: 'success',
              duration: 2000
            })
            router.push('/')
          } else {
            loading.value = false
            form.password = null

            if (result.data.msg === '用户名不存在') {
              form.userName = null
              nextTick(() => {
                userFocus.value.focus()
              })
            } else {
              nextTick(() => {
                passFocus.value.focus()
              })
            }
          }
        }).catch(error => {
          loading.value = false
          form.password = null
          nextTick(() => {
            passFocus.value.focus()
          })
        })
      })

    }
  })
}
</script>
